package com.hitqz.robot.daemon.quartz.util;

/**
 * @author xupkun
 * @date 2025/5/13
 */
public class IdGenerator {
    private final long nodeId;
    private long lastTimestamp = -1L;
    private long lastId = 0;

    private static final long NODE_BITS = 10;
    private static final long SEQUENCE_BITS = 12;
    private static final long MAX_SEQUENCE = ~(-1L << SEQUENCE_BITS);

    public IdGenerator(long nodeId) {
        this.nodeId = nodeId << SEQUENCE_BITS;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis();
        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨");
        }
        if (timestamp == lastTimestamp) {
            lastId = lastId & MAX_SEQUENCE;
        } else {
            lastId = 0;
        }
        lastTimestamp = timestamp;
        return (timestamp << (NODE_BITS + SEQUENCE_BITS))
                | nodeId
                | lastId;
    }
}
